//
//  XLCommitInputController.m
//  XiangLove
//
//  Created by 宋振 on 2018/8/9.
//  Copyright © 2018年 BAOMIHUA.COM. All rights reserved.
//

#import "XLCommitInputController.h"
#import <IQKeyboardManager.h>
#import "UITextView+ZWPlaceHolder.h"

#define MAXSTRINGLENGTH     15 //来限制最大输入只能100个字符

@interface XLCommitInputController () <UITextViewDelegate>

@property (nonatomic, strong) UITextView *  textView;

@end

@implementation XLCommitInputController
{
    //限制字数
    NSInteger textNum;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationItem.title = @"编辑";
    
    [self showBackButton:NULL];
    
    //设置界面显示
    [self initUI];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = NO;
    manager.shouldResignOnTouchOutside = NO;
    manager.shouldToolbarUsesTextFieldTintColor = NO;
    manager.shouldShowToolbarPlaceholder = NO;
    manager.enableAutoToolbar = NO;
    
    if (self.style == 1) {
        textNum = 12;
    }else{
        textNum = 50;
    }
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = YES;
    manager.shouldResignOnTouchOutside = YES;
    manager.shouldToolbarUsesTextFieldTintColor = YES;
    manager.shouldShowToolbarPlaceholder = YES;
    manager.enableAutoToolbar = YES;
    
}

#pragma mark        - - - 设置控件显示 - - -

/**
 设置保存按钮
 */
- (void)setRightButton
{
    UIButton *saveButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 44)];
    
    [saveButton setTitle:@"保存" forState:(UIControlStateNormal)];
    [saveButton setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
    
    [saveButton addTarget:self action:@selector(saveAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:saveButton];
}



/**
 设置主要控件显示
 */
- (void)initUI
{
    //设置右边保存按钮
    [self setRightButton];
    
    
    self.textView = [[UITextView alloc] initWithFrame:CGRectMake(15, 15, ScreenWidth-30, self.view.bounds.size.height/2)];
    
    self.textView.delegate = self;
    
    self.textView.font = [UIFont systemFontOfSize:17.0f];
    
    self.textView.textColor = [UIColor darkGrayColor];
    
    self.textView.placeholder = self.placehoder;
    
    self.textView.editable = YES;
    
    self.textView.layer.borderWidth = 0;
    
    [self.view addSubview:self.textView];
    
}

#pragma mark        - - - Actions - - -

//保存事件
- (void)saveAction:(UIButton *)sender
{
    NSLog(@"点击保存按钮");
    
    NSDictionary *dic;
    
    if (self.style==1) {
        
        if (self.textView.text.length <= 0 || [self isEmpty:_textView.text ] == YES) {
            [MBProgressHUD showContent:@"昵称不可以为空！"];
            
            return;
        }
        
        dic = @{
                @"UserId":K_DEFULT([XLAccountManager shareInstance].model.Id),
                @"NickName":K_DEFULT(self.textView.text),
                @"Age":[NSString stringWithFormat:@"%ld",self.model.Age],
                @"HostCity":K_DEFULT(self.model.HostCity),
                @"Introduction":K_DEFULT(self.model.Introduction)
                };
        
    }else if (self.style == 2){
        
        dic = @{
                @"UserId":K_DEFULT([XLAccountManager shareInstance].model.Id),
                @"NickName":K_DEFULT(self.model.NickName),
                @"Age":[NSString stringWithFormat:@"%ld",self.model.Age],
                @"HostCity":K_DEFULT(self.model.HostCity),
                @"Introduction":K_DEFULT(self.textView.text)
                };
        
    }
    
    [[[XLHTTPSessionManager sharedManager] XLV2POST:@"Api/v2/UserInfo/UpdateUserInfo" parameters:dic resultClass:nil] subscribeNext:^(id x) {
        
        
        if (x) {
            NSLog(@"修改成功");
            if (self.editTextBlock) {
                self.editTextBlock(K_DEFULT(self.textView.text));
            }
            
            [self.navigationController popViewControllerAnimated:YES];
        }
        
        
        
    } error:^(NSError *error) {
        
        NSLog(@"修改失败");
        [HelpTool startTipViewWithText:@"保存失败" duration:1 type:kTipViewTypeNone];
    }];
    
    
    
}

- (BOOL)isEmpty:(NSString *) str {
    
    if (!str) {
        
        return true;
        
    } else {
        
        NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
        
        NSString *trimedString = [str stringByTrimmingCharactersInSet:set];
        
        if ([trimedString length] == 0) {
            
            return true;
            
        } else {
            
            if (trimedString.length > 0) {
                self.textView.text = K_DEFULT(trimedString);
            }
            
            return false;
            
        }
        
    }
    
}

#pragma mark        --- UITextViewDelegate ---

- (void)textViewDidChange:(UITextView *)textView
{
    NSString *lang = [[[UITextInputMode activeInputModes] firstObject] primaryLanguage];//当前的输入模式
    
    if ([lang isEqualToString:@"zh-Hans"])
    {
        UITextRange *range = [textView markedTextRange];
        UITextPosition *start = range.start;
        UITextPosition*end = range.end;
        NSInteger selectLength = [textView offsetFromPosition:start toPosition:end];
        NSInteger contentLength = textView.text.length - selectLength;
        
        if (contentLength > textNum)
        {
            textView.text = [textView.text substringToIndex:textNum];
            [MBProgressHUD showContent:[NSString stringWithFormat:@"最多%ld个字",textNum]];
        }
        
    }else{
        if (textView.text.length > textNum)
        {
            textView.text = [textView.text substringToIndex:textNum];
            [MBProgressHUD showContent:[NSString stringWithFormat:@"最多%ld个字",textNum]];
        }
    }

}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    
    NSInteger maxLineNum = 1;
    
    if (self.style == 1) {
        maxLineNum = 1;
    }else{
        maxLineNum = 5;
    }
    
    NSString *textString = self.textView.text;
    CGSize fontSize = [textString sizeWithAttributes:@{NSFontAttributeName:self.textView.font}];
    
    NSString* newText = [textView.text stringByReplacingCharactersInRange:range withString:text];
    CGSize tallerSize = CGSizeMake(self.textView.frame.size.width-15,textView.frame.size.height*2);
    
    CGSize newSize = [newText boundingRectWithSize:tallerSize
                                           options:NSStringDrawingUsesLineFragmentOrigin
                                        attributes:@{NSFontAttributeName: textView.font}
                                           context:nil].size;
    NSInteger newLineNum = newSize.height / fontSize.height;
    if ([text isEqualToString:@"\n"]) {
        newLineNum += 1;
    }
    
    if ((newLineNum <= maxLineNum)
        && newSize.width < textView.frame.size.width-15)
    {
        return YES;
    }else{
        
        return NO;
    }
}

@end
